package com.wehealth.electrocardiograph_two_client.activity;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.wehealth.electrocardiograph_two_client.R;
import com.wehealth.three.lib_connect.base.EcgBaseActivity;
import com.wehealth.three.lib_connect.utils.ECGDataUtil;
import com.wehealth.three.lib_common.utils.ResUtlis;
import com.wehealth.three.lib_common.utils.StatusBarUtil;
import com.wehealth.three.lib_common.widget.UIProgressDialog;
import com.wehealth.three.lib_connect.enums.ECGDataDiagnosisType;
import com.wehealth.three.lib_connect.data.ECGData;
import com.wehealth.three.lib_connect.data.ResultPassHelper;
import com.wehealth.three.lib_connect.utils.EcgFileUtil;


import java.text.ParseException;
import java.text.SimpleDateFormat;

public class EcgReportActivity extends EcgBaseActivity implements View.OnClickListener {

    private final int MEASURE_HAVE_INTERFERENCE = 94;//测量中有干扰

    private ECGData unUploadEcg;
    private ECGData ecgData;
    private TextView result, heart, measureTimeView, classResult, adviceTV;
    private Button overBtn;
    private UIProgressDialog uiProgressDialog;
    private String filePath;
    private final String ECG_DATA_SAVE_NAME = "filename";
    ProgressDialog upLoadEcgDialog;

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MEASURE_HAVE_INTERFERENCE://测量中有干扰
                    showDialog(getResources().getString(R.string.friend_notify), getResources().getString(R.string.ecg_report_interference), getResources().getString(R.string.ok));
                    break;

            }
        }
    };

    @Override
    protected void onCreate(Bundle saveInstanceState) {
        super.onCreate(saveInstanceState);
        setContentView(R.layout.activity_ecg_report);
        StatusBarUtil.INSTANCE.setStatusBar(this, false, ResUtlis.INSTANCE.getColor(R.color.title_back_color), false);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        filePath = getIntent().getStringExtra(ECG_DATA_SAVE_NAME);
        ecgData = (ECGData) getIntent().getSerializableExtra("ecg");
        uiProgressDialog = new UIProgressDialog(this);
        uiProgressDialog.setCanceledOnTouchOutside(false);
        uiProgressDialog.setCancelable(false);
        upLoadEcgDialog = new ProgressDialog(this);
        upLoadEcgDialog.setCancelable(false);
        upLoadEcgDialog.setCanceledOnTouchOutside(false);
        initView();
        parseXMLEcgData(filePath);
    }

    private void initView() {
        measureTimeView = findViewById(R.id.textView_collectionTime_normal);
        result = findViewById(R.id.textView_diag_result);
        classResult = findViewById(R.id.textView_diag_class);
        heart = findViewById(R.id.textView_heartbeat_number);
        overBtn = findViewById(R.id.report_ecg_over);
        adviceTV = findViewById(R.id.textView_wehealth_advice);
        result.setMovementMethod(ScrollingMovementMethod.getInstance());
        overBtn.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.report_ecg_over) {
            this.finish();
        }
    }

    /**
     * 模拟数据显示
     **/
    @SuppressWarnings("deprecation")
    private void initEcgView(ECGData ecg) {
        if (ecg != null) {
            measureTimeView.setText(ecg.getTime().toLocaleString());
            heart.setText(String.valueOf(ecg.getHeartRate()));
            String resultStr = "";
            String classStr = "";
            classStr = ECGDataUtil.getClassByJson(ecg.getAutoDiagnosisResult());
            resultStr = ECGDataUtil.getResultByJson(ecg.getAutoDiagnosisResult());

            if (TextUtils.isEmpty(resultStr)) {
                classResult.setText(getResources().getString(R.string.ecg_report_no_analysis));
                result.setText(getResources().getString(R.string.ecg_report_no_analysis));
                return;
            }
            classResult.setText(classStr);
            result.setText(resultStr);
            if ("分析失败".equals(resultStr)) {
                return;
            }
            ResultPassHelper rph = null;//FileUtils.obtainWarnLevelMap(this, resultStr);
            //没有找到对应的级别
            rph = new ResultPassHelper();
            if (classStr.contains("正常")) {
                rph.setName("一");
            } else {
                rph.setName("二");
            }
            if (ecg.getHeartRate() > 100 || ecg.getHeartRate() < 60) {
                String hint = getResources().getString(R.string.abnormal_heart_rate);
                rph.setValue(hint);
            } else {
                String hint = getResources().getString(R.string.normal_heart_rate);
                rph.setValue(hint);
            }
            showECGWarn(rph);
        }
    }

    private void showECGWarn(ResultPassHelper rph) {
        if ("三".equals(rph.getName())) {
            adviceTV.setText(rph.getValue());
        }
        if ("二".equals(rph.getName())) {
            adviceTV.setText(rph.getValue());
        }
        if ("一".equals(rph.getName())) {
            adviceTV.setText(rph.getValue());
        }
    }

    /**
     * 根据地址解析数据并保存
     **/
    private void parseXMLEcgData(String path) {
        unUploadEcg = getPraseEcgData(path);
        initEcgView(unUploadEcg);
        String waveQuality = unUploadEcg.getDoctorComment();
        if ("-1".equals(waveQuality) || "-2".equals(waveQuality)) {
            mHandler.sendEmptyMessage(MEASURE_HAVE_INTERFERENCE);
            return;
        }
        unUploadEcg.setDoctorComment(null);

    }


    @SuppressWarnings("deprecation")
    @SuppressLint("SimpleDateFormat")
    private ECGData getPraseEcgData(String path) {
        ECGData newData = EcgFileUtil.parse2Data(path);
        newData.setRequestedDiagnosisType(ECGDataDiagnosisType.auto.ordinal());
        String timeStr = path.substring(path.lastIndexOf("/") + 1).replace(".xml", "");
        SimpleDateFormat sdFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        try {
            newData.setTime(sdFormat.parse(timeStr));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        newData.setLatitude(-1);
        newData.setLongitude(-1);
        newData.setVersion(1);

        return newData;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (upLoadEcgDialog.isShowing()) {
                return false;
            }
            if (uiProgressDialog.isShowing()) {
                return false;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    public void isWait(String string) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(string);
        builder.setMessage(getResources().getString(R.string.ecg_report_prompt_click_ok));
        builder.setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setCancelable(false);
        builder.show();
    }

    private void showDialog(String title, String message, String posiBtn) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setCancelable(false);
        builder.setPositiveButton(posiBtn,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        EcgReportActivity.this.finish();
                    }

                });
        builder.show();
    }


}
